<script lang="tsx">
/**
 * 搜索组件
 */
export default {
  name: "search-form"
}
</script>

<script lang="tsx" setup>
import {ref, watch} from "vue"
import SearchFormManager from "./search-form-manager.ts"
import Render from "../../core/render/index.vue"

/**
 * 定义props
 */
const propsData = defineProps<{
  searchFormModel: SearchFormManager<any>;
  reflections?: any;
}>()

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: 'refreshTableData'): void
}>()

/**
 * 搜索表单组件
 */
const searchFormModel = ref<SearchFormManager<any>>()

/**
 * 搜索表单数据
 */
const searchFormData: any = ref({})

/**
 * 重置
 */
const handleReset = () => {
  searchFormData.value = {}
  emit('refreshTableData')
}

/**
 * 筛选
 */
const handleSearch = () => {
  emit('refreshTableData')
}

/**
 * 获取筛选值
 */
const getSearchFormData = async () => {
  if (searchFormData.value?.beforeSubmit) {
    return await searchFormData.value.beforeSubmit(searchFormData.value)
  }
  return searchFormData.value
}

/**
 * 设置筛选值
 */
const setSearchFormData = async (data: any) => {
  if (searchFormData.value?.bindData) {
    searchFormData.value = await searchFormData.value.bindData(data)
  } else {
    searchFormData.value = data
  }
}

/**
 * 设置组件值
 */
const handleSetData = (item?: any) => {
  if (item) {
    searchFormData.value[item.key] = item.value
  }
}

/**
 * 监视
 */
watch(() => propsData.searchFormModel, function (newValue: any) {
  if (newValue) {
    searchFormModel.value = newValue
  }
}, {
  deep: true,
  immediate: true
})

/**
 * 暴露
 */
defineExpose({
  getSearchFormData,
  setSearchFormData
})
</script>

<template>
  <div class="search-form">
    <div class="form-box">
      <el-scrollbar>
        <div class="form-list">
          <div v-for="(item,index) of searchFormModel?.els" v-show="!item.hide" :key="index" class="form-item">
            <Render :data="searchFormData" :item="item" :reflections="propsData.reflections" @setData="handleSetData" v-bind="$attrs"/>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <el-button class="form-button" @click="handleReset">重置</el-button>
    <el-button class="form-button" type="primary" @click="handleSearch">筛选</el-button>
  </div>
</template>

<style lang="scss" scoped>
.search-form {
  flex: 0;
  display: flex;

  .form-box {
    max-width: 1400px;

    .form-list {
      display: flex;

      .form-item {
        min-width: 220px;
        padding: 5px;
      }
    }
  }

  .form-button {
    flex: 0;
    margin: 5px;
  }
}
</style>